<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores'
import { onMounted, ref } from 'vue'
import { updateUserInfoAPI } from '@/api/user'

// 获取用户信息 pinia
const formRef = ref(null)
const userStore = useUserStore()
onMounted(() => userStore.getUserInfo())

// 表单校验
const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称必须是 2 到 10 位的字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '请输入正确的邮箱格式',
      trigger: 'blur'
    }
  ]
}
// 表单提交
const onSubmit = async () => {
  // 表单校验
  await formRef.value.validate()
  // 发送请求
  await updateUserInfoAPI(userStore.userInfo)
  // 提示用户
  ElMessage.success('更新用户信息成功')
}
</script>

<template>
  <page-container title="基本资料">
    <el-form :model="userStore.userInfo" :rules="rules" ref="formRef">
      <el-form-item label="登录名称">
        <el-input
          :label="userStore.userInfo.username"
          v-model="userStore.userInfo.username"
          disabled
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          :label="userStore.userInfo.nickname"
          v-model="userStore.userInfo.nickname"
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input
          :label="userStore.userInfo.email"
          v-model="userStore.userInfo.email"
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-button type="primary" @click="onSubmit">提交修改</el-button>
    </el-form>
  </page-container>
</template>
